package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"testGin/entity"
	"testGin/tool"
)

func NoType(c *gin.Context) {
	slice1 := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}
	var srr []string
	// 获取用户登录信息
	authorization := c.GetHeader("Authorization")

	user := new(entity.User)
	info, _ := tool.ParseToken(authorization)
	GetDB().Where("id = ?", info.UserId).First(&user)

	srr = strings.Split(user.Type, ",")
	srr = difference(slice1, srr)

	var types []entity.Type
	var type_temp []entity.Type

	GetDB().Find(&types)

	for i := 0; i < len(srr); i++ {
		iii, _ := strconv.Atoi(srr[i])
		type_temp = append(type_temp, types[iii-1])
	}

	c.JSON(http.StatusOK, tool.R{
		200, "ok", type_temp,
	})
}

// 求交集
func intersect(slice1, slice2 []string) []string {
	m := make(map[string]int)
	nn := make([]string, 0)
	for _, v := range slice1 {
		m[v]++
	}

	for _, v := range slice2 {
		times, _ := m[v]
		if times == 1 {
			nn = append(nn, v)
		}
	}
	return nn
}

// 求差集
func difference(slice1, slice2 []string) []string {
	m := make(map[string]int)
	nn := make([]string, 0)
	inter := intersect(slice1, slice2)
	for _, v := range inter {
		m[v]++
	}
	for _, value := range slice1 {
		times, _ := m[value]
		if times == 0 {
			nn = append(nn, value)
		}
	}
	return nn
}

// 个人中心关闭推荐框
func CloseIsCommend(c *gin.Context) {
	loginUser := entity.GetUser(c)
	result := GetDB().Model(&entity.User{}).Where("id = ?", loginUser.Id).Update("is_commend", loginUser.IsCommend)
	if result.RowsAffected == 1 {
		c.JSON(http.StatusOK, tool.R{
			200, "ok", nil,
		})
	} else {
		c.JSON(http.StatusBadRequest, tool.R{
			400, "fail! Not Change", nil,
		})
	}
}
